package com.md.application.assembler;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.md.domain.model.po.RoleApis;
import com.md.model.po.Apis;
import com.md.model.response.system.ApiResponse;
import com.md.model.system.PageResponse;
import com.md.util.ClassUtils;
import com.md.value.enums.AuthEnum;
import com.md.value.enums.ModuleEnum;
import lombok.experimental.UtilityClass;
import org.apache.commons.compress.utils.Lists;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 刘骄阳
 * 2022-12-21 17:35
 */
@UtilityClass
public class ApiAssembler {

  /**
   * po构建为响应实体
   *
   * @param apiIPage 分页
   * @return 响应实体
   */
  public static PageResponse<ApiResponse> buildPo2Response(final IPage<Apis> apiIPage) {
    List<Apis> records = apiIPage.getRecords();
    List<ApiResponse> list = Lists.newArrayList();
    records.forEach(api -> {
      ApiResponse apiResponse = ClassUtils.source2Target(api, ApiResponse.class);
      apiResponse.setAuth(AuthEnum.of(api.getAuth()));
      apiResponse.setModule(ModuleEnum.of(api.getModule()).getMessage());
      list.add(apiResponse);
    });
    return PageResponse.of(apiIPage.getPages(), apiIPage.getTotal(), (int) apiIPage.getSize(),
      (int) apiIPage.getCurrent(), list);
  }

  /**
   * 构建绑定的响应实体
   *
   * @param roleId  角色id
   * @param apiList apiIdList
   * @return 要入库的api实体
   */
  public static List<RoleApis> buildInsertRoleApi(final Long roleId, final List<Long> apiList) {
    return apiList.stream().map(apiId -> {
      RoleApis temp = new RoleApis();
      temp.setRoleId(roleId);
      temp.setApiId(apiId);
      return temp;
    }).collect(Collectors.toList());
  }

  /**
   * 构建绑定的响应实体
   *
   * @param apiList apiIdList
   * @param apiMap  api映射
   * @return 要入库的api实体
   */
  public static List<ApiResponse> buildApiResponse(final List<Apis> apiList,
                                                   final Map<Long, RoleApis> apiMap) {
    return apiList.stream().map(api -> {
      RoleApis roleApis = apiMap.get(api.getId());
      ApiResponse apiResponse = ClassUtils.source2Target(api, ApiResponse.class);
      apiResponse.setModule(ModuleEnum.of(api.getModule()).getMessage());
      apiResponse.setAuth(AuthEnum.of(api.getAuth()));
      apiResponse.setExtendsParentRole(roleApis.getExtendsParentRole());
      return apiResponse;
    }).collect(Collectors.toList());
  }
}
